package gui;

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;



public class InternalTextPane extends JInternalFrame {
	public InternalTextPane(String title) {
		super();
		this.initialize(title);
	}

	public InternalTextPane(File file) {
		super();
		this.file = file;
		this.initialize(this.file.getPath());
		this.readFile();
		this.textArea.setText(this.fileContent);
	}

	public void setText(String text) {
		this.textArea.setText(text);
	}

	private void readFile() {
		String read = "";
		if (file != null) {
			try {
				FileReader reader = new FileReader(file);
				BufferedReader bufreader = new BufferedReader(reader);
				while ((read = bufreader.readLine()) != null) {
					fileContent += read + "\n";
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void initialize(String title) {
		this.setTitle(title);
		this.setResizable(true);
		this.setClosable(true);
		this.setMaximizable(true);
		this.setIconifiable(true);
		this.setSize(300, 300);
		this.setLocation(20, 20);
		this.setVisible(true);
		
		this.textArea = new JEditorPane();
		this.editorPane = new JEditorPane();
		
		
		this.scrollPane = new JScrollPane(this.textArea);
		this.textArea.setContentType("text/java");
		this.getContentPane().setLayout(new BorderLayout());
		this.getContentPane().add(this.scrollPane);
		this.getContentPane().doLayout();
	}

	public File getFile() {
		return this.file;
	}

	public void saveFile() {
		if (this.file != null) {
			try {
				saveWriter = new FileWriter(file);
				saveWriter.write(this.textArea.getText());
				saveWriter.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void saveAs(File file) {
		try {
			saveWriter = new FileWriter(file);
			saveWriter.write(this.textArea.getText());
			saveWriter.flush();
			this.file = file;
			this.setTitle(file.getPath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getText() {
		return textArea.getText();
	}

	private JEditorPane editorPane = null;
	private JEditorPane textArea = null;
	private JScrollPane scrollPane = null;
	private File file = null;
	private String fileContent = "";
	private FileWriter saveWriter = null;
}
